// @ts-nocheck
import {useState, useEffect} from 'react'
import {Modal, Form, Input, message, Row, Col, Select, Upload} from 'antd'
import {PlusOutlined} from "@ant-design/icons";
import {createClient, modifyClient} from "@/services/client";
import DistrictSelect from '@/components/Select/DistrictSelect'
import SubDistrictSelect from '@/components/Select/SubDistrictSelect'
import CommunitySelect from "@/components/Select/CommunitySelect";
import AddressSelect from "@/components/Select/AddressSelect";
import {checkIdCard} from '@/tools/tool'

// @ts-ignore
const CreateModify = ({data, mode, onClose, onOk, visible}) => {
  const [form] = Form.useForm()
  const [files, setFiles] = useState([])
  const [district, setDistrict] = useState(null)
  const [subDistrict, setSubDistrict] = useState(null)
  const [community, setCommunity] = useState(null)
  const [address, setAddress] = useState(null)
  const [back, setBack] = useState(true)
  const {TextArea} = Input;
  const {Option} = Select;
  const init = () => {
    setDistrict(null)
    setSubDistrict(null)
    setCommunity(null)
    setAddress(null)
    setBack(true)
  }
  const handleOk = () => {
    form.validateFields().then(values => {

      if (mode === 'create') {
        const formData = new FormData();
        formData.append('img', values.upload_certificate.file.originFileObj)
        formData.append('name', values.name)
        formData.append('telephone', values.telephone)
        formData.append('certificate_type', values.certificate_type)
        formData.append('certificate', values.certificate)
        formData.append('district', values.district)
        formData.append('subdistrict', values.subdistrict)
        formData.append('community', values.community)
        formData.append('address', values.address)
        formData.append('detail_address', values.detail_address)

        createClient(formData).then(res => {
          if (res.status === 200) {
            onOk()
            init()
            message.success(res.message).then()
          } else {
            message.error(res.message).then()
          }
        })

      } else {
        const body = {
          name: values.name,
          telephone: values.telephone,
          district: values.district,
          subdistrict: values.subdistrict,
          community: values.community,
          address: values.address,
          detail_address: values.detail_address
        }
        modifyClient({...body, client_id: data.client_id}).then(res => {
          if (res.status === 200) {
            onOk()
            init()
            message.success(res.message).then()
          } else {
            message.error(res.message).then()
          }
        })
      }


    })
  }
  useEffect(() => {
    if (visible) {
      if (mode == 'create') {
        form.resetFields()
        setFiles([])
      } else {
        setDistrict(data.district)
        setSubDistrict(data.subdistrict)
        setCommunity(data.community)
        setAddress(data.address)
        form.setFieldsValue({
          name: data.name,
          telephone: data.telephone,
          certificate_type: data.certificate_type,
          certificate: data.certificate,
          district: data.district,
          subdistrict: data.subdistrict,
          community: data.community,
          address: data.address,
          detail_address: data.detail_address,

        })
      }
    } else {
      form.resetFields()
    }
  }, [visible, mode])
  const onAddressSelect = (e) => {
    const {district_id, subdistrict_id, community_id} = e
    setBack(true)
    setCommunity(community_id)
    setSubDistrict(subdistrict_id)
    setDistrict(district_id)
    form.setFieldsValue({district: district_id, subdistrict: subdistrict_id, community: community_id})
  }
  const onCommunitySelect = (e) => {
    const {district_id, subdistrict_id} = e
    setBack(true)
    setSubDistrict(subdistrict_id)
    setDistrict(district_id)
    form.setFieldsValue({district: district_id, subdistrict: subdistrict_id})
  }

  const onCancel = () => {
    onClose()
    init()
  }
  return (
    <Modal
      title={mode === 'create' ? '新增客户' : '修改客户'}
      maskClosable={false}
      destroyOnClose
      width={'40vw'}
      visible={visible}
      onCancel={onCancel}
      onOk={handleOk}
      keyboard={false}
      mask={false}
    >
      <Form form={form} labelCol={{span: 6}} wrapperCol={{span: 14}} autoComplete="off">
        <Row>
          <Col span={12}>
            <Form.Item label="客户名称" name="name" rules={[{required: true, message: '请输入客户名称'}]}>
              <Input placeholder={'请输入客户名称'} allowClear/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="手机号" name="telephone" >
              <Input maxLength={11} placeholder={'请输入手机号'} allowClear/>
            </Form.Item>
          </Col>
          {mode === 'create' ? <><Col span={12}>
            <Form.Item label="证件类型" name="certificate_type" rules={[{required: true, message: '请选择证件类型'}]}>
              <Select
                showSearch
                placeholder="请选择证件类型"
                optionFilterProp="children"
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
              >
                <Option value={1}>居民身份证</Option>
                <Option value={2}>护照</Option>
                <Option value={3}>营业执照</Option>
              </Select>
            </Form.Item>
          </Col>
            <Col span={12}>
              <Form.Item label="证件号码" name="certificate" rules={[{required: true, message: '请输入证件号码'}, ({getFieldValue}) => ({
                validator(_, value) {
                  if(getFieldValue('certificate_type') === 1){
                    if(!value || checkIdCard(value)){
                      return Promise.resolve();
                    } else {
                      return Promise.reject(new Error('身份证验证失败!'));
                    }
                  }else{
                    return Promise.resolve();
                  }
                }})]}>
                <Input placeholder={'请输入证件号码'} allowClear/>
              </Form.Item>
            </Col></> : null}
          <Col span={12}>
            <Form.Item label="所属区域" name="district" rules={[{required: true, message: '请选择所属区域'}]}>
              <DistrictSelect onChange={(e) => {
                setBack(false);
                setDistrict(e)
              }} defaultValue={district}/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="所属街道" name="subdistrict" rules={[{required: true, message: '请选择所属街道'}]}>
              <SubDistrictSelect onChange={(e) => {
                setBack(false);
                setSubDistrict(e)
              }} district={district} defaultValue={subDistrict} back={back}/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="所属园区" name="community" rules={[{required: true, message: '请选择所属园区'}]}>
              <CommunitySelect onSelect={(e) => onCommunitySelect(e)} onChange={(e) => {
                setCommunity(e)
              }}
                               subDistrict={subDistrict} district={district} defaultValue={community} back={back}/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="蓝牌地址" name="address" rules={[{required: true, message: '请选择蓝牌地址'}]}>
              <AddressSelect onSelect={(e) => onAddressSelect(e)} onChange={(e) => setAddress(e)} community={community}
                             district={district}
                             subDistrict={subDistrict} back={back}
                             defaultValue={address}/>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item label="详细地址" name="detail_address" rules={[{required: true, message: '请输入详细地址'}]}>
              <TextArea autoSize allowClear placeholder={'请输入详细地址'}/>
            </Form.Item>
          </Col>
          {mode === 'create' ? <Col span={12}>
            <Form.Item label={"上传证件"} name="upload_certificate">
              <Upload
                listType="picture-card"
                accept=".jpg, .jpeg, .png"
                onChange={({fileList}) => setFiles(fileList)}
              >
                {files.length >= 1 ? null : <div>
                  <PlusOutlined/>
                  <div style={{marginTop: 8}}>上传证件</div>
                </div>}
              </Upload>
            </Form.Item>
          </Col> : null}
        </Row>

      </Form>
    </Modal>
  );
};

export default CreateModify;
